import 'package:dartx/dartx.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:gluz/app/data/area_entity.dart';
import 'package:gluz/app/data/dictionary_entity.dart';
import 'package:gluz/app/data/shop/shop_category_entity.dart';

import '../../../../app_session.dart';
import '../../../common/aliyun_oss.dart';
import '../../../common/bottom_modal_sheet.dart';
import '../../../common/common_button.dart';
import '../../../common/resource_picker_sheet.dart';
import '../../../data/api_response.dart';
import '../../../data/auth_entity.dart';
import '../../../data/user_profile_entity.dart';
import '../../../utils/colors.dart';
import '../../../utils/http_util.dart';
import '../../../utils/toast_util.dart';

mixin AuthBaseController implements GetxController {
  final UserProfileEntity user = app.getUser()!;

  /// 认证实体
  AuthEntity authEntity = AuthEntity();

  /// 头像
  final RxString avatarPath = ''.obs;
  final RxString selectedAuthType = '个人'.obs;

  /// 个人认证信息
  final TextEditingController userNickPhoneController = TextEditingController(
    text: app.getUser()?.nickName,
  );
  final TextEditingController userPhoneController = TextEditingController(
    text: app.getUser()?.phoneNumber,
  );
  final TextEditingController userNameController = TextEditingController();
  final TextEditingController userIdNumController = TextEditingController();

  /// 店铺信息
  final TextEditingController introduceController =
      TextEditingController(); // 店铺简介
  final TextEditingController jingyingfanweiController =
      TextEditingController();
  final TextEditingController fahuodizhiController = TextEditingController();
  final RxString dianputoutuPath = ''.obs; // 店铺头图
  final RxString shengchanxukePath = ''.obs;
  final RxString hangyezizhiPath = ''.obs;

  /// 公司信息
  final TextEditingController enterpriseNameController =
      TextEditingController();
  final TextEditingController creditCodeController = TextEditingController();
  final RxString businessLicensePath = ''.obs;
  final TextEditingController companyAddressController =
      TextEditingController();
  final TextEditingController currentEmployeesController =
      TextEditingController();
  final TextEditingController occupiedAreaController = TextEditingController();
  final RxString companyPhotoPath = ''.obs;
  final RxString companyVideoPath = ''.obs;
  String get companyVideoPathFrame {
    if (companyVideoPath.isEmpty) return '';
    final videoUri = Uri.parse(companyVideoPath.value);
    final newUri = videoUri.replace(
      queryParameters: {
        'x-oss-process': 'video/snapshot,t_1,f_jpg,m_fast,ar_auto'
      },
    );
    return newUri.toString();
  }
  final TextEditingController legalRepresentativeNameController =
      TextEditingController();
  final TextEditingController legalRepresentativeIdController =
      TextEditingController();
  final RxString legalIdCardFrontPath = ''.obs;
  final RxString legalIdCardBackPath = ''.obs;
  final RxString isManagerSameAsLegal = '是'.obs;
  final RxString idCardFrontPath = ''.obs;
  final RxString idCardBackPath = ''.obs;

  /// 银行信息
  final TextEditingController corporateAccountNameController =
      TextEditingController();
  final TextEditingController bankInfoController = TextEditingController();
  final TextEditingController bankAccountController = TextEditingController();

  /// 采购商信息
  // 采购范围
  final RxString caigoufanwei = ''.obs;


  /// 货代信息
  List<TransportAgentTask> roadMapList = [TransportAgentTask()];
  final RxList<String> serverItemList = RxList<String>();
  final RxList<String> serverItemSelectedList = RxList<String>();
  final TextEditingController otherServerDescController = TextEditingController();
  final RxString shoufeibiaozhun = ''.obs;
  final TextEditingController serverDescController = TextEditingController();

  /// 服务商信息
  // 提供服务范围使用jingyingfanweiController,

  /// 翻译
  final RxString suozaidi = ''.obs;
  final TextEditingController ziyuanhenengliController = TextEditingController();
  final RxList<String> languageList = RxList<String>();
  final RxList<String> languageSelectedList = RxList<String>();
  final RxList<String> zhuanyefanweiList = RxList<String>();
  final RxList<String> zhuanyefanweiSelectedList = RxList<String>();
  final RxString fyshoufei = ''.obs;
  final RxList<String> citySelectedList = RxList<String>();


  @override
  void onInit() {
    List<DictionaryEntity>? list = app.dictionaryEntityList('bus_service_item');
    if (list != null) {
      serverItemList.addAll(list.map((e) => e.dictLabel).toList());
    }

    List<DictionaryEntity>? languages = app.dictionaryEntityList('bus_language_ability');
    if (languages != null) {
      languageList.addAll(languages.map((e) => e.dictLabel).toList());
    }

    List<DictionaryEntity>? zhuanyes = app.dictionaryEntityList('bus_professional_scope');
    if (zhuanyes != null) {
      zhuanyefanweiList.addAll(zhuanyes.map((e) => e.dictLabel).toList());
    }
  }



  Widget getStatusWidget() {
    String? status = authEntity.authStatus;
    if (status.toInt() == 0) {
      return const SizedBox.shrink();
    }
    String assets = 'assets/images/auth/auth_pass.png';
    if (status.toInt() == 1) {
      assets = 'assets/images/auth/auth_pass.png';
    } else if (status.toInt() == 2) {
      assets = 'assets/images/auth/auth_reject.png';
    } else {
      assets = 'assets/images/auth/auth_reviewing.png';
    }
    return Positioned(
      top: 0,
      right: 0,
      width: 80,
      height: 80,
      child: Image.asset(assets),
    );
  }

  Future<void> requestAuthInfo() async {
    ToastUtil.showLoading();
    AuthEntity? authEntity = await app.http.request(
      path: '/api/auth/getUserAuth/${user.id}',
      method: Method.get,
      fromJson: (e) => AuthEntity.fromJson(e),
    );
    if (authEntity != null) {
      this.authEntity = authEntity;
      avatarPath.value = authEntity.avatar.isNotEmpty
          ? authEntity.avatar
          : user.avatar;
      userNickPhoneController.text = authEntity.nickName.isNotEmpty
          ? authEntity.nickName
          : user.nickName;
      userPhoneController.text = authEntity.phoneNumber.isNotEmpty
          ? authEntity.phoneNumber
          : user.phoneNumber;
      selectedAuthType.value = authEntity.type == '2' ? '公司'.tr : '个人'.tr;
      if (authEntity.personal != null) {
        userNameController.text = authEntity.personal!.fullName;
        userIdNumController.text = authEntity.personal!.idNumber;
        idCardFrontPath.value = authEntity.personal!.idPhotoFront;
        idCardBackPath.value = authEntity.personal!.idPhotoBack;
      }

      if (authEntity.supplier != null) {
        introduceController.text = authEntity.supplier!.introduction;
        jingyingfanweiController.text = authEntity.supplier!.mainBus;
        fahuodizhiController.text = authEntity.supplier!.shipmentAreaName;
        dianputoutuPath.value = authEntity.supplier!.headImg;
        shengchanxukePath.value = authEntity.supplier!.prodLicense;
        hangyezizhiPath.value = authEntity.supplier!.qualifications;

        currentEmployeesController.text = authEntity.supplier!.employees
            .toString();
        occupiedAreaController.text = authEntity.supplier!.coverArea;
        companyPhotoPath.value = authEntity.supplier!.companyImg;
        companyVideoPath.value = authEntity.supplier!.companyAvi;
      }

      if (authEntity.enterprise != null) {
        enterpriseNameController.text = authEntity.enterprise!.entName;
        creditCodeController.text = authEntity.enterprise!.licenseNumber;
        businessLicensePath.value = authEntity.enterprise!.licensePhoto;
        companyAddressController.text = authEntity.enterprise!.address;

        legalRepresentativeNameController.text =
            authEntity.enterprise!.legalPerson;
        legalRepresentativeIdController.text =
            authEntity.enterprise!.legalIdNumber;
        legalIdCardFrontPath.value = authEntity.enterprise!.legalIdPhotoFront;
        legalIdCardBackPath.value = authEntity.enterprise!.legalIdPhotoBack;

        corporateAccountNameController.text = authEntity.enterprise!.bankName;
        bankInfoController.text = authEntity.enterprise!.bankAccountName;
        bankAccountController.text = authEntity.enterprise!.bankAccountNumber;
      }

      if (authEntity.purchaser != null) {
        introduceController.text = authEntity.purchaser!.introduction;
        caigoufanwei.value = authEntity.purchaser!.goodsTypeId;
        businessLicensePath.value = authEntity.purchaser!.licenseImg;
      }

      if (authEntity.transportAgent != null) {
        companyPhotoPath.value = authEntity.transportAgent!.companyImg;
        companyVideoPath.value = authEntity.transportAgent!.companyAvi;
        introduceController.text = authEntity.transportAgent!.introduction;
        serverItemSelectedList.value = authEntity.transportAgent!.serviceItem.split(',');
        otherServerDescController.text = authEntity.transportAgent!.serviceMemo;
        shoufeibiaozhun.value = authEntity.transportAgent!.feeImg;
        serverDescController.text = authEntity.transportAgent!.protection;
        businessLicensePath.value = authEntity.transportAgent!.busLicense;
        roadMapList = authEntity.transportAgent!.transportAgentTask;
      }

      if (authEntity.servicer != null) {
        jingyingfanweiController.text = authEntity.servicer!.undertake;
        businessLicensePath.value = authEntity.servicer!.busLicense;
        // hangyezizhiPath.value =
      }

      if (authEntity.translator != null) {
        suozaidi.value = authEntity.translator!.currentCity;
        ziyuanhenengliController.text = authEntity.translator!.resourceAbility;
        languageSelectedList.value = authEntity.translator!.languageAbility.split(',');
        zhuanyefanweiSelectedList.value = authEntity.translator!.professionalScope.split(',');
        fyshoufei.value = authEntity.translator!.feeStandards;
        citySelectedList.value = authEntity.translator!.familiarCity.split(',');
        hangyezizhiPath.value = authEntity.translator!.professionalCer;
      }

      update();
    }
  }

  void disposeResources() {
    enterpriseNameController.dispose();
    creditCodeController.dispose();
    companyAddressController.dispose();
    currentEmployeesController.dispose();
    occupiedAreaController.dispose();
    legalRepresentativeNameController.dispose();
    legalRepresentativeIdController.dispose();
    corporateAccountNameController.dispose();
    bankInfoController.dispose();
    introduceController.dispose();
    fahuodizhiController.dispose();
  }

  // 上传头像
  void uploadAvatar() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadAvatar(
            filePath: result.filePath!,
            userId: user.id,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            avatarPath.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  // 更新认证类型
  void updateAuthType(String type) {
    selectedAuthType.value = type;
  }

  // 上传营业执照
  void uploadBusinessLicense() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            businessLicensePath.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  Future<void> onTapCaigoufanwei() async {
    ToastUtil.showLoading();
    List<ShopCategoryEntity> shopList = await app.getShopCategory();
    showModalBottomSheet(
      context: Get.context!,
      builder: (ctx) {
        return StatefulBuilder(
          builder: (context, state) {
            return Container(
              height: 0.5.sh,
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.only(
                  topLeft: const Radius.circular(10.0),
                  topRight: const Radius.circular(10.0),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.all(15.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text('取消'.tr, style: TextStyle(color: Colors.white)),
                        Text(
                          '采购范围'.tr,
                          style: TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        InkWell(onTap: Get.back, child: Text('取消'.tr)),
                      ],
                    ),
                  ),
                  Expanded(
                    child: SingleChildScrollView(
                      child: Wrap(
                        spacing: 8,
                        children: shopList
                            .map(
                              (e) => FilledButton(
                                style: FilledButton.styleFrom(
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(4),
                                  ),
                                  padding: const EdgeInsets.all(8),
                                  backgroundColor: e.isSelected ? AppColors.color_278AFF : AppColors.color_EEEEEE,
                                ),
                                onPressed: () {
                                  e.isSelected = !e.isSelected;
                                  state((){});
                                },
                                child: Text(e.description, style: TextStyle(color: e.isSelected ? Colors.white : Colors.black,),),
                              ),
                            ).toList(),
                      ),
                    ),
                  ),

                  SafeArea(
                    child: Container(
                      margin: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
                      child: GLGradientButton(
                        onPressed: () {
                          String values = shopList.filter((e) => e.isSelected).map((e) => e.description).toList().join(',');
                          caigoufanwei.value = values;
                          Get.back();
                        },
                        child: const Text(
                          '确定',
                          style: TextStyle(color: Colors.white),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            );
          }
        );
      },
    );
  }

  // 上传公司照片
  void uploadCompanyPhoto() {
    ResourcePickerSheet.show(
      allowMultiple: true,
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            List<String> values = [];
            if (companyPhotoPath.isNotEmpty) {
              values.add(companyPhotoPath.value);
            }
            values.add(uploadRes.url!);
            companyPhotoPath.value = values.join(',');
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  void onTapCompanyPhotoDelete(int index) {
    List values = companyPhotoPath.value.split(',');
    values.removeAt(index);
    companyPhotoPath.value = values.join(',');
  }

  // 上传公司视频
  void uploadCompanyVideo() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: true,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadVideo(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            companyVideoPath.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  void onTapCompanyVideoDelete(int index) {
    companyVideoPath.value = '';
  }

  // 上传身份证正面
  void uploadIdCardFront() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            idCardFrontPath.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  // 上传身份证背面
  void uploadIdCardBack() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            idCardBackPath.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  // 上传店铺头图
  void uploadDianputoutu() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            dianputoutuPath.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  void onTapDianputoutuDelete(int index) {
    dianputoutuPath.value = '';
  }

  // 上传生产许可
  void uploadShengchanxuke() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            shengchanxukePath.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  void onTapShengchanxukeDelete(int index) {
    shengchanxukePath.value = '';
  }

  // 上传行业资质
  void uploadHangyezizhi() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            List<String> values = [];
            if (hangyezizhiPath.isNotEmpty) {
              values.add(hangyezizhiPath.value);
            }
            values.add(uploadRes.url!);
            hangyezizhiPath.value = values.join(',');
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  void onTapHangyezizhiDelete(int index) {
    List values = hangyezizhiPath.value.split(',');
    values.removeAt(index);
    hangyezizhiPath.value = values.join(',');
  }

  // 更新管理人与法人是否同一人
  void updateManagerSameAsLegal(String value) {
    isManagerSameAsLegal.value = value;
  }

  // 上传法人身份证正面
  void uploadLegalIdCardFront() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            legalIdCardFrontPath.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  // 上传法人身份证背面
  void uploadLegalIdCardBack() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            legalIdCardBackPath.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  void addRoadMap() {
    if (roadMapList.last.startPoint == null || roadMapList.last.endPoint == null) {
      ToastUtil.show('请完善路线信息');
      return;
    }
    roadMapList.add(TransportAgentTask());
    update();
  }

  /// 选择服务项目
  void updateServerItem(String value) {
    if (serverItemSelectedList.contains(value)) {
      serverItemSelectedList.remove(value);
    } else {
      serverItemSelectedList.add(value);
    }
    update();
  }

  /// 上传收费标准
  void onTapShoufeibiaozhun() {
    ResourcePickerSheet.show(
      allowFile: false,
      allowVideo: false,
      onResult: (result) async {
        if (result.isSuccess) {
          logger.i('选择的文件路径: ${result.filePath}');
          ToastUtil.showLoading();
          final uploadRes = await AliyunOSSUploader.uploadImage(
            filePath: result.filePath!,
            onProgress: (int send, int total) {
              logger.i('上传进度:${send.toDouble() / total.toDouble()}');
            },
          );
          if (uploadRes.isSuccess) {
            shoufeibiaozhun.value = uploadRes.url!;
            ToastUtil.dismiss();
          } else {
            ToastUtil.dismiss();
          }
        } else {
          logger.i('选择失败: ${result.errorMessage}');
        }
      },
    );
  }

  void onTapShoufeibiaozhunDelete(int index) {
    shoufeibiaozhun.value = '';
  }

  /// 点击所在地
  void onTapSuozaidi() {
    BottomModalSheet.showAreaSector((areaEntity) {
      suozaidi.value = areaEntity.mergename;
    });
  }

  void onTapLanguageOptions(String value) {
    if (languageSelectedList.contains(value)) {
      languageSelectedList.remove(value);
    } else {
      languageSelectedList.add(value);
    }
    update();
  }

  void onTapZhuanyefanweiOptions(String value) {
    if (zhuanyefanweiSelectedList.contains(value)) {
      zhuanyefanweiSelectedList.remove(value);
    } else {
      zhuanyefanweiSelectedList.add(value);
    }
    update();
  }

  void onTapFyShoufei() {
    BottomModalSheet.showTranslationPrice(fyshoufei.value, (entity) {
      fyshoufei.value = entity.dictValue;
    });
  }

  void onTapShuxichengshi() {
    BottomModalSheet.showAreaSector((areaEntity) {
      citySelectedList.add(areaEntity.name);
      update();
    });
  }

  void onTapRemoveShuxichengshi(String v) {
    citySelectedList.remove(v);
    update();
  }

  // 提交表单
  void submitForm() async {
    ToastUtil.showLoading();
    authEntity.userId = user.id;
    authEntity.avatar = avatarPath.value;
    authEntity.type = selectedAuthType.value == '个人' ? '1' : '2';

    // 个人信息相关
    authEntity.personal ??= AuthPersonal();
    authEntity.personal?.fullName = userNameController.text;
    authEntity.personal?.idNumber = userIdNumController.text;
    authEntity.personal?.idPhotoFront = idCardFrontPath.value;
    authEntity.personal?.idPhotoBack = idCardBackPath.value;
    authEntity.supplier ??= AuthSupplier();
    authEntity.supplier?.userId = user.id;
    authEntity.supplier?.introduction = introduceController.text;
    authEntity.supplier?.mainBus = jingyingfanweiController.text; // 经营范围
    authEntity.supplier?.shipmentAreaName = fahuodizhiController.text; // 发货地址
    authEntity.supplier?.headImg = dianputoutuPath.value; // 店铺头图
    authEntity.supplier?.prodLicense = shengchanxukePath.value; // 生产许可
    authEntity.supplier?.qualifications = hangyezizhiPath.value; // 行业资质

    // 企业信息相关
    authEntity.enterprise ??= AuthEnterprise();
    authEntity.enterprise?.entName = enterpriseNameController.text;
    authEntity.enterprise?.licenseNumber = creditCodeController.text;
    authEntity.enterprise?.licensePhoto = businessLicensePath.value;
    authEntity.enterprise?.address = companyAddressController.text;
    authEntity.supplier ??= AuthSupplier();
    authEntity.supplier?.employees =
        currentEmployeesController.text.toIntOrNull() ?? 0;
    authEntity.supplier?.coverArea = occupiedAreaController.text;
    authEntity.supplier?.companyImg = companyPhotoPath.value;
    authEntity.supplier?.companyAvi = companyVideoPath.value;
    authEntity.enterprise?.legalPerson = legalRepresentativeNameController.text;
    authEntity.enterprise?.legalIdNumber = legalRepresentativeIdController.text;
    authEntity.enterprise?.legalIdPhotoFront = legalIdCardFrontPath.value;
    authEntity.enterprise?.legalIdPhotoBack = legalIdCardBackPath.value;
    authEntity.enterprise?.bankAccountName =
        corporateAccountNameController.text;
    authEntity.enterprise?.bankName = bankInfoController.text;
    authEntity.enterprise?.bankAccountNumber = bankAccountController.text;

    // 采购商
    authEntity.purchaser ??= AuthPurchaser();
    authEntity.purchaser?.userId = user.id;
    authEntity.purchaser?.introduction = introduceController.text;
    authEntity.purchaser?.goodsTypeId = caigoufanwei.value;
    authEntity.purchaser?.licenseImg = businessLicensePath.value;

    // 运输货代
    authEntity.transportAgent ??= AuthTransportAgent();
    authEntity.transportAgent?.userId = user.id;
    authEntity.transportAgent?.companyImg = companyPhotoPath.value;
    authEntity.transportAgent?.companyAvi = companyVideoPath.value;
    authEntity.transportAgent?.introduction = introduceController.text;
    authEntity.transportAgent?.serviceItem = serverItemSelectedList.join(',');
    authEntity.transportAgent?.serviceMemo = otherServerDescController.text;
    authEntity.transportAgent?.feeImg = shoufeibiaozhun.value;
    authEntity.transportAgent?.protection = serverDescController.text;
    authEntity.transportAgent?.busLicense = businessLicensePath.value;
    authEntity.transportAgent?.transportAgentTask = roadMapList;

    // 服务商
    authEntity.servicer ??= AuthServicer();
    authEntity.servicer?.userId = user.id;
    authEntity.servicer?.undertake = jingyingfanweiController.text;
    authEntity.servicer?.busLicense = businessLicensePath.value;

    // 翻译
    authEntity.translator ??= AuthTranslator();
    authEntity.translator?.userId = user.id;
    authEntity.translator?.currentCity = suozaidi.value;
    authEntity.translator?.resourceAbility = ziyuanhenengliController.text;
    authEntity.translator?.languageAbility = languageSelectedList.join(',');
    authEntity.translator?.professionalScope = zhuanyefanweiSelectedList.join(',');
    authEntity.translator?.feeStandards = fyshoufei.value;
    authEntity.translator?.familiarCity = citySelectedList.join(',');
    authEntity.translator?.professionalCer = hangyezizhiPath.value;

    ApiResponse? apiResponse = await app.http.request(
      path: '/api/auth/userAuth',
      method: Method.post,
      params: authEntity.toJson(),
      fromJson: (e) => ApiResponse.fromJson(e),
    );
    if (apiResponse?.success == true) {
      ToastUtil.show('成功');
      Get.back();
    }
  }
}
